from flask import Blueprint, request, jsonify, session, render_template, redirect, url_for
import requests
import re
from datetime import datetime, timedelta
import random
import math
from flask_login import login_required, current_user

# 创建蓝图
search_bp = Blueprint('search', __name__, url_prefix='/search')

# 搜索页面
@search_bp.route('/')
@login_required
def index():
    return render_template('search.html', username=current_user.username)

# 搜索类型映射
SEARCH_TYPES = {
    'all': '',  # 默认无类型参数
    'image': 'image',
    'video': '',  # Google CSE API 不支持直接的视频搜索类型
    'news': '',   # Google CSE API 不支持直接的新闻搜索类型
    'web': ''  # 网页搜索也是默认的
}

# 每页结果数量
RESULTS_PER_PAGE = 10

# 搜索API接口 - 处理搜索请求并返回结果
@search_bp.route('/api', methods=['GET'])
@login_required
def search():
    # 从配置中获取 Google Search API 信息
    from flask import current_app
    GOOGLE_CSE_URL = current_app.config.get('GOOGLE_CSE_URL', 'https://www.googleapis.com/customsearch/v1')
    GOOGLE_API_KEY = current_app.config.get('GOOGLE_API_KEY', '')
    SEARCH_ENGINE_ID = current_app.config.get('SEARCH_ENGINE_ID', '')

    print(f"GOOGLE_CSE_URL: {GOOGLE_CSE_URL}")
    print(f"GOOGLE_API_KEY: {GOOGLE_API_KEY}")
    print(f"SEARCH_ENGINE_ID: {SEARCH_ENGINE_ID}")

    query = request.args.get('query')
    search_type = request.args.get('type', 'all')  # 默认为全部
    page = int(request.args.get('page', '1'))  # 获取页码，默认为第1页
    
    if not query:
        return jsonify({'error': '未提供搜索查询'}), 400

    if not GOOGLE_API_KEY or not SEARCH_ENGINE_ID:
        return jsonify({'error': '未配置 Google API 密钥或搜索引擎 ID'}), 500

    # 构建 API 请求参数
    params = {
        'q': query,
        'key': GOOGLE_API_KEY,
        'cx': SEARCH_ENGINE_ID,
        'num': RESULTS_PER_PAGE,  # 每页结果数量
        'start': (page - 1) * RESULTS_PER_PAGE + 1  # 计算起始索引
    }
    
    # 添加特定的查询参数
    if search_type == 'video':
        # 对于视频搜索，添加视频相关关键词以提高相关性
        params['q'] = f"{query} video"
    elif search_type == 'news':
        # 对于新闻搜索，添加新闻相关关键词
        params['q'] = f"{query} news"
    
    # 图片搜索类型
    if search_type == 'image' and SEARCH_TYPES[search_type]:
        params['searchType'] = SEARCH_TYPES[search_type]
    
    try:
        # 发送请求到 Google Custom Search API
        response = requests.get(GOOGLE_CSE_URL, params=params)
        response.raise_for_status()  # 检查响应状态
        
        data = response.json()
        
        # 提取总结果数和分页信息
        total_results = int(data.get('searchInformation', {}).get('totalResults', '0'))
        total_pages = math.ceil(total_results / RESULTS_PER_PAGE)
        
        # 提取搜索结果
        results = []
        if 'items' in data:
            for item in data['items']:
                # 基础结果对象
                result = {
                    'title': item.get('title', '无标题'),
                    'link': item.get('link', '无链接'),
                    'snippet': item.get('snippet', '无描述')
                }
                
                # 提取并格式化显示 URL
                if 'displayLink' in item:
                    result['displayLink'] = item['displayLink']
                
                # 根据搜索类型添加额外信息
                if search_type == 'image' and 'image' in item:
                    # 图片搜索
                    result['thumbnail'] = item['image'].get('thumbnailLink', '')
                    if 'image' in item:
                        result['imageWidth'] = item['image'].get('width', 0)
                        result['imageHeight'] = item['image'].get('height', 0)
                
                elif search_type == 'video':
                    # 视频搜索 - 一些信息可能需要进一步处理或模拟
                    # 提取缩略图（如果有）
                    if 'pagemap' in item and 'cse_thumbnail' in item['pagemap']:
                        result['thumbnail'] = item['pagemap']['cse_thumbnail'][0].get('src', '')
                    elif 'pagemap' in item and 'cse_image' in item['pagemap']:
                        result['thumbnail'] = item['pagemap']['cse_image'][0].get('src', '')
                    else:
                        # 使用占位图
                        result['thumbnail'] = ''
                    
                    # 视频时长（模拟数据）
                    result['duration'] = f"{random.randint(1, 20)}:{random.randint(10, 59)}"
                
                elif search_type == 'news':
                    # 新闻搜索
                    # 提取来源和日期
                    if 'pagemap' in item and 'metatags' in item['pagemap'] and item['pagemap']['metatags']:
                        metatags = item['pagemap']['metatags'][0]
                        # 尝试提取发布时间
                        pub_date = None
                        for date_key in ['article:published_time', 'publishdate', 'date', 'og:pubdate']:
                            if date_key in metatags:
                                pub_date = metatags[date_key]
                                break
                        
                        if pub_date:
                            # 尝试格式化日期
                            try:
                                # 计算相对时间（例如"3小时前"）
                                # 使用通用时间格式
                                pub_time = datetime.fromisoformat(pub_date.replace('Z', '+00:00'))
                                now = datetime.now()
                                diff = now - pub_time
                                
                                if diff.days > 365:
                                    result['pubTime'] = f"{diff.days // 365}年前"
                                elif diff.days > 30:
                                    result['pubTime'] = f"{diff.days // 30}个月前"
                                elif diff.days > 0:
                                    result['pubTime'] = f"{diff.days}天前"
                                elif diff.seconds // 3600 > 0:
                                    result['pubTime'] = f"{diff.seconds // 3600}小时前"
                                else:
                                    result['pubTime'] = f"{diff.seconds // 60}分钟前"
                            except:
                                # 如果解析失败，使用通用时间
                                result['pubTime'] = "近期"
                    
                    # 提取缩略图
                    if 'pagemap' in item and 'cse_thumbnail' in item['pagemap']:
                        result['thumbnail'] = item['pagemap']['cse_thumbnail'][0].get('src', '')
                    elif 'pagemap' in item and 'cse_image' in item['pagemap']:
                        result['thumbnail'] = item['pagemap']['cse_image'][0].get('src', '')
                
                # 对于网页搜索，提取丰富结果（如评分、价格等）
                if search_type in ['all', 'web']:
                    # 如果有rich snippets，提取它们
                    if 'pagemap' in item:
                        pagemap = item['pagemap']
                        
                        # 提取缩略图，如果有的话
                        if 'cse_thumbnail' in pagemap:
                            result['thumbnail'] = pagemap['cse_thumbnail'][0].get('src', '')
                        elif 'cse_image' in pagemap:
                            result['thumbnail'] = pagemap['cse_image'][0].get('src', '')
                
                results.append(result)
        
        # 返回包含分页信息的结果
        response_data = {
            'results': results,
            'pagination': {
                'current_page': page,
                'total_pages': total_pages,
                'total_results': total_results,
                'results_per_page': RESULTS_PER_PAGE
            }
        }
        
        return jsonify(response_data)
        
    except requests.exceptions.RequestException as e:
        print(f"网络请求错误: {str(e)}")
        return jsonify({'error': f'API 请求失败: {str(e)}'}), 500
    except Exception as e:
        print(f"处理请求时发生错误: {str(e)}")
        return jsonify({'error': f'处理请求时发生错误: {str(e)}'}), 500 